<template>
  <div class="search-result-container">
    <!-- 头部搜索栏 -->
    <van-sticky>
      <div class="search-header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="search-box">
          <van-search
            v-model="searchInput"
            placeholder="请输入搜索关键词"
            shape="round"
            background="#f7f8fa"
            @search="handleSearch"
          />
        </div>
      </div>
    </van-sticky>

    <!-- 动态分类筛选区域 -->
    <div class="category-section" v-if="categories.length > 0">
      <van-tabs 
        v-model:active="activeCategory" 
        swipeable
        color="#ee0a24"
        line-width="20px"
      >
        <van-tab title="全部" name="all" />
        <van-tab 
          v-for="category in categories" 
          :key="category" 
          :title="category" 
          :name="category"
        />
      </van-tabs>
    </div>

    <!-- 搜索结果列表 -->
    <div class="result-list">
      <van-empty 
        v-if="filteredRecipes.length === 0 && !isLoading"
        description="暂无搜索结果"
        image="search"
      />
      
      <div v-else>
        <div 
          v-for="recipe in filteredRecipes" 
          :key="recipe.recipesId"  
          class="recipe-card"
          @click="goToDetail(recipe.recipesId)"
        >
          <div class="card-content">
            <!-- 菜谱封面 - 使用默认图或占位图 -->
            <div class="recipe-cover">
              <img 
                :src="recipe.recipesUrl || 'https://img.yzcdn.cn/vant/apple-1.jpg'" 
                :alt="recipe.recipesName" 
                class="cover-img"
              />
            </div>
            
            <!-- 菜谱信息 -->
            <div class="recipe-info">
              <div class="recipe-name">
                {{ recipe.recipesName }}
              </div>
              
              <div class="recipe-meta">
                <van-rate 
                  v-model="recipe.recipesRank" 
                  readonly 
                  allow-half 
                  :size="14" 
                  color="#ffd21e"
                />
                <span class="rating-text">{{ recipe.recipesRank }}分</span>
              </div>
              
              <div class="recipe-desc">
                {{ recipe.description }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Keyword_search">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { searchRecipes } from '../../api'

const router = useRouter()
const searchInput = ref('')
const searchKeyword = ref('')
const activeCategory = ref('all')
const recipes = ref([])
const categories = ref([])
const isLoading = ref(false)

// 计算过滤后的菜谱列表
const filteredRecipes = computed(() => {
  if (activeCategory.value === 'all') {
    return recipes.value
  }
  return recipes.value.filter(recipe => 
    recipe.categories && recipe.categories.includes(activeCategory.value)
  )
})

// 返回上一页
const goBack = () => router.go(-1)

// 跳转到详情页
const goToDetail = (id) => {
  router.push({ path: '/recipe_datail', query: { recipeId:id } })
}

// 处理搜索
const handleSearch = async () => {
  if (!searchInput.value.trim()) {
    showToast('请输入搜索关键词')
    return
  }
  
  searchKeyword.value = searchInput.value.trim()
  activeCategory.value = 'all'
  isLoading.value = true
  
  try {
    const response = await searchRecipes(searchKeyword.value)
    
    // 处理返回数据
    if (response && response.recipes) {
      recipes.value = response.recipes.map(recipe => ({
        ...recipe,
        // 确保评分是数字
        recipesRank: Number(recipe.recipesRank) || 0
      }))
      
      // 从返回数据中提取分类（假设后端返回的categories是分类名称数组）
      categories.value = response.categories || []
    } else {
      recipes.value = []
      categories.value = []
    }
  } catch (error) {
    showToast('搜索失败')
    console.error('搜索错误:', error)
    recipes.value = []
    categories.value = []
  } finally {
    isLoading.value = false
  }
}

// 初始化时从路由获取搜索关键词
onMounted(() => {
  const keyword = router.currentRoute.value.query.keyword
  if (keyword) {
    searchInput.value = keyword
    searchKeyword.value = keyword
    handleSearch()
  }
})
</script>

<style scoped>
.search-result-container {
  padding-bottom: 20px;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f7f8fa;
}

.back-icon {
  font-size: 20px;
  margin-right: 10px;
}

.search-box {
  flex: 1;
}

.category-section {
  margin-top: 10px;
}

.recipe-card {
  padding: 12px;
  border-bottom: 1px solid #f5f5f5;
}

.card-content {
  display: flex;
}

.recipe-cover {
  width: 100px;
  height: 80px;
  margin-right: 12px;
  border-radius: 4px;
  overflow: hidden;
}

.cover-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.recipe-info {
  flex: 1;
}

.recipe-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 6px;
  display: -webkit-box;
  line-clamp: 1;  
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.recipe-meta {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.rating-text {
  margin-left: 8px;
  font-size: 12px;
  color: #ff976a;
}

.recipe-desc {
  font-size: 12px;
  color: #999;
  display: -webkit-box;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>